/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.security.dynamic;

import vip.dexian.core.security.PermsGrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 自定义权限映射器， 该映射器返回 {@link PermsGrantedAuthority}。
 *
 * @author 挺好的 2023年06月06日 10:39
 */
public final class AuthorityMapper implements GrantedAuthoritiesMapper {

    /**
     * 返回转换后的权限 {@link PermsGrantedAuthority}， 如果 authorities为空，则返回一个空的 set 集合
     *
     * @param authorities
     *         权限列表
     *
     * @return 转换后的权限
     */
    @Override
    public Set <PermsGrantedAuthority> mapAuthorities (Collection <? extends GrantedAuthority> authorities) {
        HashSet <PermsGrantedAuthority> mapped = new HashSet <>(authorities.size());

        if (CollectionUtils.isEmpty(authorities)) {
            return mapped;
        }

        for (GrantedAuthority grantedAuthority : authorities) {
            PermsGrantedAuthority authority = (PermsGrantedAuthority) grantedAuthority;
            mapped.add(this.mapAuthority(authority.getAuthority(), authority.getAuthorities()));
        }

        return mapped;
    }

    private PermsGrantedAuthority mapAuthority (String name, List <String> authorities) {
        return new PermsGrantedAuthority(name, authorities);
    }
}
